package com.jy.appmarket.activity;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;
import it.gmariotti.cardslib.library.view.PullToRefreshListView.RefreshingListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.cards.BaseUICard;
import com.jy.appmarket.cards.CardsUtils;
import com.jy.appmarket.cards.DownloadableUICard;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.CardPageNetEngine;
import com.jy.appmarket.network.engine.cachestrategy.CacheStrategy;
import com.jy.appmarket.network.resultdata.PageResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.receiver.PushReceiver;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.ActivateStatistics;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.view.LoadingView;
import com.jy.appmarket.view.LoadingView.OnClickListener;
import com.umeng.analytics.MobclickAgent;

public class CardPageActivity extends DownloadActivity implements NetTaskListener, OnClickListener, RefreshingListener {
	private static final String TAG = CardPageActivity.class.getSimpleName();
	public static final String EXTRA_PATH = "page_path";
	public static final String EXTRA_PARAMS = "page_params";
	public static final String EXTRA_SOURCE = "page_source";
	public static final String EXTRA_TITLE = "title";
	public static final String PUSH_ID = "push_id";

	private CardListView mListview;
	private CardArrayAdapter mCardsAdapter;
	private ArrayList<Card> mCardsArray = new ArrayList<Card>();
	private NetTask mNetTask;

	private LoadingView mLoadingView;
	private int mPageIndex = 1;
	private boolean mIsFooterRefresh = false;
	private long mDataVersion;
	private String mPath;
	// private String mSource;
	private String mTitle;
	private Map<String, String> mParams;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_card_page);
		getExtras();
		initTitle();
		initLoadingView();
		initListView();
		loadData(true);
		ActivateStatistics.ActivateFrom(this, this.getClass().getSimpleName());
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(mTitle);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}

	private void getExtras() {
		if (getIntent() != null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				mPath = extras.getString(EXTRA_PATH);
				mTitle = extras.getString(EXTRA_TITLE);
				// mSource = extras.getString(EXTRA_SOURCE);

				Bundle bundle = getIntent().getBundleExtra(EXTRA_PARAMS);
				if (bundle != null && !bundle.isEmpty()) {
					mParams = new HashMap<String, String>();
					for (String key : bundle.keySet()) {
						mParams.put(key, bundle.getString(key));
					}
				}

				String pushId = extras.getString(PUSH_ID);

				// if(FileDownloadModel.PUSH_APP.equalsIgnoreCase(mComeFrom)) {
				// NotificationUtil.cancelNotification(this,
				// PushReceiver.NOTIFICATION_APP_ID);
				// }
				// String pushId = b.getString(PUSH_ID);
				if (!TextUtils.isEmpty(pushId)) {
					PushReceiver.sendConsumeBroadcast(this, pushId, 1);
				}

			}
		}
	}

	private void loadData(boolean loadFirstPage) {
		int pageIndex = mPageIndex;
		if (loadFirstPage) {
			pageIndex = 1;
			mDataVersion = 0;
			mLoadingView.showWaitView(R.string.ptr1_loading_wait);
			mListview.setVisibility(View.GONE);
			mLoadingView.setVisibility(View.VISIBLE);
		}
		CardPageNetEngine engine = new CardPageNetEngine(mPath, mDataVersion, pageIndex, mParams);
		engine.setCacheStrategy(new CacheStrategy(true, CacheStrategy.THREE_HOUR));
		mNetTask = new NetTask(this, engine, 1);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	private void initListView() {
		mListview = findViewById(R.id.discovery_fragment_cardlist);
		mListview.setEmptyView(mLoadingView);
		mListview.needToRefreshOnFooter(true);
		mListview.needToRefreshOnHeader(false);
		mListview.setRefreshListener(this);
		mListview.setVisibility(View.GONE);

		mCardsAdapter = new CardArrayAdapter(this, mCardsArray);
		mCardsAdapter.setInnerViewTypeCount(100);
		mListview.setAdapter(mCardsAdapter);
	}

	private void initLoadingView() {
		mLoadingView = findViewById(R.id.loading_view_layout);
		mLoadingView.setOnClickListener(this);
		mLoadingView.showWaitView(getString(R.string.loading_wait));
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		PageResult resultData = (PageResult) engine.getResultData();
		if (!resultData.isOK()) {
			if (mPageIndex == 1) {
				mLoadingView.showErrorView(R.string.load_failed_retry);
			}
		} else {
			List<com.jy.app.market.idata.card.Card> cards = resultData.getCards();
			if (cards == null || cards.size() == 0) {
				if (mLoadingView.getVisibility() == View.VISIBLE) {
					mLoadingView.showErrorView(R.string.no_data);
					return;
				}
			} else {
				mDataVersion = resultData.getDataVersion();
				for (com.jy.app.market.idata.card.Card card : cards) {
					BaseUICard uiCard = CardsUtils.getCardInstance(this, card);
					if (uiCard == null) {
						LogUtil.w(TAG, "Unsupport " + card.getType() + " at " + mCardsArray.size());
						continue;
					}
					uiCard.setIndex(mCardsArray.size());
					if (uiCard instanceof DownloadableUICard) {
						DownloadableUICard c = (DownloadableUICard) uiCard;
						c.setListView(mListview);
						addFileListener(c);
					}
					ApkSource as = createApkSource();
					as.setIndex(uiCard.getIndex());
					uiCard.setApkSource(as);
					mCardsArray.add(uiCard);

				}
				mCardsAdapter.notifyDataSetChanged();
				mListview.footerRefreshingCompleted();
				mListview.setVisibility(View.VISIBLE);
				mLoadingView.setVisibility(View.GONE);
				mPageIndex++;
				if (mIsFooterRefresh) {
					mIsFooterRefresh = false;
				}

				if (resultData.getPageNo() >= resultData.getTotalPage()) {
					mListview.needToRefreshOnFooter(false);
				}
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		if (mCardsAdapter.isEmpty()) {
			mListview.setVisibility(View.GONE);
			mLoadingView.showErrorView(getString(R.string.ptrl_refresh_fail));
		} else {
			if (mIsFooterRefresh) {
				mListview.footerRefreshError();
				mIsFooterRefresh = false;
			}
		}
		Toast.makeText(this, R.string.network_error, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onTaskRunCanceled(int tag) {

	}

	@Override
	public void onLoadingViewClick(View view) {
		loadData(true);
	}

	@Override
	public void onHeaderRefreshing() {
		// nothing todo
	}

	@Override
	public void onFooterRefreshing() {
		mIsFooterRefresh = true;
		loadData(false);
	}

	private ApkSource createApkSource() {
		if (mPath == null) {
			return null;
		}

		ApkSource as = new ApkSource(mPath);
		as.setDataVersion(mDataVersion);
		if ("tag".equals(mPath) && mParams != null) {
			as.setTagName(mParams.get("tagName"));
		}
		return as;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void goBack() {
		AppMarketApplication app = (AppMarketApplication) getApplication();
		if (app.isAppRunning()) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setClass(this, MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			startActivity(intent);
		} else {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		}
		finish();
	}
}